package 剑指Offer.medium;

import java.util.Scanner;

public class 把字符串转换为整数 {
    static class Solution {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            String next = sc.nextLine();
            System.out.println(strToInt(next));
        }

        public static int strToInt(String str) {
            //删除前后空格
            str = str.trim();
            if (str.length() == 0) return 0;
            //确定数值在字符串中的范围
            int index = 0;
            int sign = 1;
            int res = 0;
            if (str.charAt(index) == '+' || str.charAt(index) == '-') {
                sign = str.charAt(index) == '-' ? -1 : 1;
                index++;
            }
            //确定结束点
            for (; index < str.length(); index++) {
                int digit = str.charAt(index) - '0';
                if (digit < 0 || digit > 9) break;
                //越界处理
                if (res > Integer.MAX_VALUE / 10 || (res == Integer.MAX_VALUE / 10 && digit > Integer.MAX_VALUE % 10)) {
                    return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
                } else {
                    res = res * 10 + digit;
                }
            }
            return sign * res;
        }
    }
}
